import { createContext, useContext, ReactNode, useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

type AuthContextType = {
  isAuthenticated: boolean;
  token: string | null;
  login: (token: string) => void;
  logout: () => void;
};

const AuthContext = createContext<AuthContextType>({
  isAuthenticated: false,
  token: localStorage.getItem('authToken'),
  login: () => {},
  logout: () => {}
});

export function AuthProvider({ children }: { children: ReactNode }) {
  const [token, setToken] = useState<string | null>(localStorage.getItem('authToken'));
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const storedToken = localStorage.getItem('authToken');
    if (storedToken) {
      setToken(storedToken);
    }
  }, [location]);

  // const [user, setUser] = useState<User | null>(() => {
  //   const token = localStorage.getItem('authToken');
  //   return token ? { name: "User", token } : null;
  // });

  const login = (token: string, redirectPath?: string) => {
    localStorage.setItem('authToken', token);
    setToken(token);
  };

  const logout = () => {
    // 实现登出逻辑
    localStorage.removeItem('authToken'); // 清除 token
    setToken(null);
    navigate('/login');
    // setUser(null);
  };

  return (
    <AuthContext.Provider
      value={{ isAuthenticated: !!token, token, login, logout }}
    >
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => useContext(AuthContext);